package org.example.forum.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.ArticleMapper;
import org.example.forum.dao.BoardMapper;
import org.example.forum.dao.UserMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Article;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.service.IArticleService;
import org.example.forum.service.IBoardService;
import org.example.forum.service.IUserService;
import org.example.forum.utils.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    //避免循环引用
    @Resource
    private IUserService userService;

    @Resource
    private IBoardService boardService;

    @Resource
    private ArticleMapper articleMapper;

    @Override
    public void create(Article article) {
        if(article==null || article.getUserId()==null || article.getBoardId()==null
        || StringUtil.isEmpty(article.getTitle()) || StringUtil.isEmpty(article.getContent())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setLikeCount(0);
        article.setReplyCount(0);
        article.setVisitCount(0);
        article.setDeleteState((byte)0);
        article.setState((byte)0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //写入数据库
        int row = articleMapper.insert(article);
        if(row!=1) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_CREATE));
        }
        //更新用户发帖数
        User user = userService.selectById(article.getUserId());
        if(user==null) {
            log.warn(ResultCode.FAILED_CREATE.toString());

            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_CREATE)+"发帖失败,userId="+article.getUserId());
        }
        userService.addOneArticleCountById(user.getId());
        //更新板块发帖数
        Board board = boardService.selectById(article.getBoardId());
        if(board==null) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_CREATE)+"发帖失败,boardId="+article.getBoardId() );
        }
        boardService.addOneArticleCountById(board.getId());
        //打印日志
        log.info(ResultCode.SUCCESS.toString()+"userId="+article.getUserId()+",boardId="+article.getBoardId()+",articleId="+article.getId()+" 发帖成功");

        //throw new ApplicationException(AppResult.failure("测试回滚"));
    }

    @Override
    public List<Article> selectAll() {
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        //非空校验
        if(boardId==null || boardId==0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检验板块是否存在
        Board board = boardService.selectById(boardId);
        if(board==null) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        return articleMapper.selectAllByBoardId(boardId);
    }

    @Override
    public Article selectDetailById(Long id) {
        if(id==null || id<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailByArticleId(id);
        if(article==null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新帖子的访问次数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
        //更新返回对象的返回次数
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        //非空校验
        if(id==null || id<=0 ||StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构造要更新的对象
        Article article = new Article();
        article.setId(id);
        article.setTitle(title);
        article.setContent(content);
        article.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(article);
        if(row!=1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public Article selectById(Long id) {
        //帖子不存在
        if(id==null || id<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        //帖子状态异常
        if(article.getDeleteState()==1 || article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_BANNED));
        }
        if(article==null) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        return article;
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(userId==null || userId<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检验用户是否存在
        User user = userService.selectById(userId);
        if(user==null || user.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
//        if (user.getState()==1){
//            log.warn(ResultCode.FAILED_USER_BANNED.toString());
//            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_BANNED));
//        }
        List<Article> articles = articleMapper.selectByUserId(userId);
        return articles;
    }

    @Override
    public void thumbsUpById(Long id) {
        if(id==null || id<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null || article.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //帖子状态异常
        if(article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
        log.info("点赞完成");
    }

    @Override
    public void deleteById(Long id) {
        if(id==null || id<=0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if(article==null || article.getDeleteState()==1 ) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte)1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1) {
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
        //更新 板块 用户 帖子数
        boardService.subOneArticleCountById(article.getBoardId());
        userService.subOneArticleCountById(article.getUserId());
        log.info("文章删除完成");
    }

    @Override
    public void addOneReplyCountById(Long id) {
        // 非空校验
        if (id == null || id <= 0) {
            // 打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 获取帖子记录
        Article article = articleMapper.selectByPrimaryKey(id);
        // 校验帖子状态
        if (article == null || article.getDeleteState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        // 帖子已封帖
        if (article.getState() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        // 回复数 = 原回复数 + 1
        updateArticle.setReplyCount(article.getReplyCount() + 1);
        updateArticle.setUpdateTime(new Date());
        // 执行更新
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectBySearchBox(String keyword) {
        if(StringUtil.isEmpty(keyword)) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        keyword="%"+keyword+"%";
        List<Article> articles = articleMapper.selectBySearchBox(keyword);
        return articles;
    }


}
